﻿using System;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Text;

namespace Pfz.ErrorHandling
{
	/// <summary>
	/// Class that stores errors related to a property.
	/// </summary>
	public sealed class PropertyErrors
	{
		/// <summary>
		/// Creates a new instance.
		/// </summary>
		public PropertyErrors(PropertyInfo property, ReadOnlyCollection<object> errors)
		{
			if (property == null)
				throw new ArgumentNullException("property");
				
			if (errors == null)
				throw new ArgumentNullException("errors");
				
			if (errors.Count == 0)
				throw new ArgumentException("errors is empty.", "errors");
		
			Property = property;
			Errors = errors;
		}
	
		/// <summary>
		/// Gets the property to which the errors are related to.
		/// </summary>
		public PropertyInfo Property { get; private set; }
		
		/// <summary>
		/// Gets the errors.
		/// </summary>
		public ReadOnlyCollection<object> Errors { get; private set; }

		/// <summary>
		/// Gets a message with all the errors together.
		/// </summary>
		public string Message
		{
			get
			{
				int count = Errors.Count;

				if (count == 1)
					return Errors[0].ToString();

				var stringBuilder = new StringBuilder();
				foreach(var error in Errors)
				{
					stringBuilder.Append(error);
					stringBuilder.Append(", ");
				}
				stringBuilder.Length -= 2;
				return stringBuilder.ToString();
			}
		}
	}
}
